/*
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include <chrono>
#include <gtest/gtest.h>
#include <mc/exception.h>
#include <mc/filesystem.h>
#include <mc/json.h>
#include <string>
#include <test_utilities/test_base.h>
#include <thread>
#include <vector>

#include "device/driver.h"
#include "device/manager.h"
#include "devmon.h"
#include "test_driver.h"
#include "topology/device_topo.h"
#include <devmon/driver_abi.h>

using namespace devmon;
using devmon_service_ptr = mc::shared_ptr<devmon::devmon_service>;

class ManagerTest : public mc::test::TestWithEngine {
public:
protected:
    static void SetUpTestSuite() {
        TestWithEngine::SetUpTestSuite();
        m_test_service->init({{"driver_path", "./opt/bmc/drivers"}});
        m_test_service->start();
        auto test_driver_ptr = new test::test_driver();
        create_driver(test_driver_ptr);
    }

    static void TearDownTestSuite() {
        m_test_service->stop();
        TestWithEngine::TearDownTestSuite();
    }

    void SetUp() override {
        TestWithEngine::SetUp();
    }

    void TearDown() override {
        // 清理对象表中的所有对象，除了根对象
        auto& object_table = m_test_service->get_object_table();

        // 多次清理确保对象被完全删除，处理依赖关系
        for (int retry = 0; retry < 3; ++retry) {
            std::vector<std::string> paths_to_remove;
            object_table.query_object(
                mc::db::query_builder(), [&paths_to_remove](mc::db::object_base& obj) {
                    try {
                        auto& abstract_obj = static_cast<mc::engine::abstract_object&>(obj);
                        auto  object_name  = std::string(abstract_obj.get_object_name());
                        auto  object_path  = std::string(abstract_obj.get_object_path());
                        // 保留根对象和根路径，只清理 /bmc/dev/Systems/ 下的测试对象
                        if (object_name != "Devmon" && object_name != "DevmonTopo" &&
                            object_name != "DevTopology" && object_path != "/bmc/dev") {
                            // 只清理 /bmc/dev/Systems/ 下的对象
                            if (object_path.find("/bmc/dev/Systems/") == 0) {
                                paths_to_remove.push_back(object_path);
                            }
                        }
                    } catch (...) {
                        // 忽略单个对象的处理错误
                    }
                    return true;
                });

            if (paths_to_remove.empty()) {
                break; // 没有更多对象需要删除
            }

            // 按路径删除对象，先删除子对象（路径更长的）
            std::sort(paths_to_remove.begin(), paths_to_remove.end(),
                      [](const std::string& a, const std::string& b) {
                          return a.length() > b.length(); // 按路径长度降序排列
                      });

            for (const auto& path : paths_to_remove) {
                try {
                    // 检查路径是否为空，避免注销无效路径
                    if (!path.empty()) {
                        // 在注销前检查对象是否仍然存在，避免注销不存在的路径导致段错误
                        bool object_exists = false;
                        object_table.query_object(
                            mc::db::query_builder(),
                            [&object_exists, &path](mc::db::object_base& obj) {
                                try {
                                    auto& abstract_obj =
                                        static_cast<mc::engine::abstract_object&>(obj);
                                    const auto object_path =
                                        std::string(abstract_obj.get_object_path());
                                    if (object_path == path) {
                                        object_exists = true;
                                        return false; // 找到后停止查询
                                    }
                                } catch (...) {
                                    // 忽略单个对象的处理错误
                                }
                                return true;
                            });
                        if (object_exists) {
                            m_test_service->unregister_object(path);
                        }
                    }
                } catch (...) {
                    // 忽略注销错误，某些对象可能已经被删除
                }
            }
        }

        // 清空func_collection缓存，避免测试用例间相互影响
        mc::expr::func_collection::get_instance().clear();

        TestWithEngine::TearDown();
    }

    static void create_driver(test::test_driver* test_driver_ptr) {
        m_test_device_driver.clear();
        m_test_device_driver.reserve(3);
        static std::string driver_name         = std::string("test_driver");
        static std::string pcie_nic_card_name  = std::string("PCIeNicCard");
        static std::string network_port_name   = std::string("NetworkPort");
        static std::string optical_module_name = std::string("OpticalModule");
        auto               pcie_nic_card       = test_driver_ptr->create(pcie_nic_card_name);
        auto               network_port        = test_driver_ptr->create(network_port_name);
        auto               optical_module      = test_driver_ptr->create(optical_module_name);
        m_test_device_driver.emplace_back(pcie_nic_card);
        m_test_device_driver.emplace_back(network_port);
        m_test_device_driver.emplace_back(optical_module);
        device_driver_factory::get_instance().set_device_driver(driver_name, &m_test_device_driver);
    }

    // 辅助方法：通过D-Bus查询设备属性，带重试机制
    static devmon_service_ptr m_test_service;
    static device_drivers     m_test_device_driver; // 声明为静态成员变量
};

// 定义静态成员变量
devmon_service_ptr ManagerTest::m_test_service =
    mc::make_shared<devmon::devmon_service>("bmc.kepler.devmon");
device_drivers ManagerTest::m_test_device_driver; // 定义静态成员变量

TEST_F(ManagerTest, add_device_success) {
    auto csr_str = mc::filesystem::read_file("./tests_data/csr/test_device.sr");
    MC_ASSERT_THROW(csr_str, mc::invalid_arg_exception, "Failed to read csr file: ${file}",
                    ("file", "./tests_data/csr/test_device.sr"));
    auto             csr_variant = mc::json::json_decode(*csr_str).as_dict();
    mc::mutable_dict connector;
    connector["SystemId"]      = 1;
    connector["GroupPosition"] = std::string("01");
    connector["Slot"]          = 1;

    device_manager::get_instance().add_device(m_test_service.get(), *csr_str, connector);

    // 直接从对象表验证每个设备是否正确注册，避免依赖D-Bus异步行为
    auto& object_table = m_test_service->get_object_table();
    struct object_expectation {
        std::string object_path;
        std::string expected_name;
    };
    std::vector<object_expectation> expectations = {
        {"/bmc/dev/Systems/1/test_device/test_card", "PCIeNicCard_1_01"},
        {"/bmc/dev/Systems/1/test_device/test_port_0", "NetworkPort_0_01"},
        {"/bmc/dev/Systems/1/test_device/test_om", "OpticalModule_0_01"}};

    for (const auto& item : expectations) {
        bool found = false;
        object_table.query_object(mc::db::query_builder(), [&](mc::db::object_base& obj) {
            auto& abstract_obj = static_cast<mc::engine::abstract_object&>(obj);
            if (std::string(abstract_obj.get_object_path()) == item.object_path) {
                found = true;
                EXPECT_EQ(std::string(abstract_obj.get_object_name()), item.expected_name);
                return false;
            }
            return true;
        });
        ASSERT_TRUE(found) << "object not found: " << item.object_path;
    }

    // 清理：移除设备
    mc::dict remove_connector{{"SystemId", 1},
                              {"GroupPosition", std::string("01")},
                              {"Slot", 1},
                              {"Unit", csr_variant["Unit"]}};
    device_manager::get_instance().remove_device(remove_connector);
    auto device_object = device_topo::get_instance().get_device_object("01");
    EXPECT_EQ(device_object, nullptr);
}

TEST_F(ManagerTest, add_device_with_topology_success) {
    auto csr_str = mc::filesystem::read_file("./tests_data/csr/topology.sr");
    MC_ASSERT_THROW(csr_str, mc::invalid_arg_exception, "Failed to read csr file: ${file}",
                    ("file", "./tests_data/csr/topology.sr"));
    auto csr_variant = mc::json::json_decode(*csr_str).as_dict();

    mc::mutable_dict connector;
    connector["SystemId"]      = 1;
    connector["GroupPosition"] = std::string("0101");
    connector["Slot"]          = 1;
    connector["Buses"]         = mc::variants{"I2c_A", "I2c_B"};

    device_manager::get_instance().add_device(m_test_service.get(), *csr_str, connector);

    auto device_object = device_topo::get_instance().get_device_object("0101");
    EXPECT_NE(device_object, nullptr);

    mc::dict remove_connector{{"SystemId", 1},
                              {"GroupPosition", std::string("0101")},
                              {"Slot", 1},
                              {"Unit", csr_variant["Unit"]}};
    device_manager::get_instance().remove_device(remove_connector);
    device_object = device_topo::get_instance().get_device_object("0101");
    EXPECT_EQ(device_object, nullptr);
}

// 测试 add_device 处理内联拓扑（包含 Anchor）场景
TEST_F(ManagerTest, add_device_inline_topology_anchor) {
    std::string csr_json = R"({
        "Unit": {
            "Type": "PCIeNicCard",
            "Name": "PCIeNicCard_Inline",
            "Compatible": ["test_driver"]
        },
        "Objects": {
            "PCIeNicCard_Inline": {
                "bmc.dev.TestInterface": {
                    "DeviceName": "inline_card"
                }
            },
            "NetworkPort_Inline": {
                "bmc.dev.TestInterface": {
                    "DeviceName": "inline_port"
                }
            },
            "Bus_I2c_Template": {
                "bmc.dev.Bus.I2c": {
                    "Id": 10
                }
            },
            "Chip_Template": {
                "bmc.dev.TestInterface": {
                    "DeviceName": "chip_inline"
                }
            }
        },
        "ManagementTopology": {
            "Anchor": {"Buses": ["Bus_I2c_Template"]},
            "Bus_I2c_Template": {"Chips": ["Chip_Template"]}
        }
    })";

    auto csr_variant = mc::json::json_decode(csr_json).as_dict();

    mc::mutable_dict connector;
    connector["SystemId"]      = 3;
    connector["GroupPosition"] = std::string("0301");
    connector["Slot"]          = 1;
    connector["Buses"]         = mc::variants{"I2c_A"};

    device_manager::get_instance().add_device(m_test_service.get(), csr_json, connector);
    auto device_object = device_topo::get_instance().get_device_object("0301");
    EXPECT_NE(device_object, nullptr);

    mc::dict remove_connector{{"SystemId", 3},
                              {"GroupPosition", std::string("0301")},
                              {"Slot", 1},
                              {"Unit", csr_variant["Unit"]}};
    device_manager::get_instance().remove_device(remove_connector);
    device_object = device_topo::get_instance().get_device_object("0301");
    EXPECT_EQ(device_object, nullptr);
}

TEST_F(ManagerTest, remove_device_requires_unit_information) {
    auto csr_str = mc::filesystem::read_file("./tests_data/csr/test_device.sr");
    MC_ASSERT_THROW(csr_str, mc::invalid_arg_exception, "Failed to read csr file: ${file}",
                    ("file", "./tests_data/csr/test_device.sr"));
    auto csr_variant = mc::json::json_decode(*csr_str).as_dict();

    mc::mutable_dict connector;
    connector["SystemId"]      = 1;
    connector["GroupPosition"] = std::string("03");
    connector["Slot"]          = 1;

    device_manager::get_instance().add_device(m_test_service.get(), *csr_str, connector);
    auto device_object = device_topo::get_instance().get_device_object("03");
    EXPECT_NE(device_object, nullptr);

    mc::dict connector_without_unit{
        {"SystemId", 1}, {"GroupPosition", std::string("03")}, {"Slot", 1}};
    EXPECT_NO_THROW(device_manager::get_instance().remove_device(connector_without_unit));
    device_object = device_topo::get_instance().get_device_object("03");
    EXPECT_NE(device_object, nullptr);

    mc::dict connector_with_unit{{"SystemId", 1},
                                 {"GroupPosition", std::string("03")},
                                 {"Slot", 1},
                                 {"Unit", csr_variant["Unit"]}};
    EXPECT_NO_THROW(device_manager::get_instance().remove_device(connector_with_unit));
    device_object = device_topo::get_instance().get_device_object("03");
    EXPECT_EQ(device_object, nullptr);
}

TEST_F(ManagerTest, remove_device_returns_when_position_missing) {
    mc::dict connector{{"SystemId", 1}};

    EXPECT_NO_THROW(device_manager::get_instance().remove_device(connector));
}

TEST_F(ManagerTest, remove_device_returns_when_device_absent) {
    mc::dict connector{{"SystemId", 1}, {"GroupPosition", std::string("FF")}};

    EXPECT_NO_THROW(device_manager::get_instance().remove_device(connector));
}

TEST_F(ManagerTest, remove_device_handles_driver_stop_failure) {
    auto csr_str = mc::filesystem::read_file("./tests_data/csr/test_device.sr");
    MC_ASSERT_THROW(csr_str, mc::invalid_arg_exception, "Failed to read csr file: ${file}",
                    ("file", "./tests_data/csr/test_device.sr"));
    auto csr_variant = mc::json::json_decode(*csr_str).as_dict();

    mc::mutable_dict connector;
    connector["SystemId"]      = 1;
    connector["GroupPosition"] = std::string("04");
    connector["Slot"]          = 1;

    device_manager::get_instance().add_device(m_test_service.get(), *csr_str, connector);
    auto device_object = device_topo::get_instance().get_device_object("04");
    EXPECT_NE(device_object, nullptr);

    // 模拟 driver 停止失败：移除驱动后再调用 remove_device
    device_driver_factory::get_instance().remove_device_driver("test_driver");

    mc::dict connector_with_unit{{"SystemId", 1},
                                 {"GroupPosition", std::string("04")},
                                 {"Slot", 1},
                                 {"Unit", csr_variant["Unit"]}};

    // 验证 remove_device 不会抛出异常，即使驱动加载失败
    EXPECT_NO_THROW(device_manager::get_instance().remove_device(connector_with_unit));

    // 当驱动加载失败时，设备对象不会被移除（因为异常处理时没有调用 remove_device_object）
    // 所以设备对象应该仍然存在
    auto residual_object = device_topo::get_instance().get_device_object("04");
    EXPECT_NE(residual_object, nullptr);

    // 恢复驱动后，再次尝试移除设备
    auto test_driver_ptr = new test::test_driver();
    create_driver(test_driver_ptr);

    // 这次应该能成功移除
    EXPECT_NO_THROW(device_manager::get_instance().remove_device(connector_with_unit));
    auto final_object = device_topo::get_instance().get_device_object("04");
    EXPECT_EQ(final_object, nullptr);
}

// ==================== device_manager::add_device 错误处理场景测试 ====================

// 测试 add_device 中 create_devices_object 失败的情况
TEST_F(ManagerTest, add_device_create_devices_object_failed) {
    // 创建一个会导致 create_devices_object 失败的 CSR（缺少 Unit 对象）
    // 当 m_objects 中缺少 m_unit.m_name 时，create_component_device 会抛出异常
    std::string csr_json = "{\n"
                           "  \"Unit\": {\n"
                           "    \"Type\": \"PCIeNicCard\",\n"
                           "    \"Name\": \"PCIeNicCard_1\",\n"
                           "    \"Compatible\": [\"test_driver\"]\n"
                           "  },\n"
                           "  \"Objects\": {\n"
                           "    \"OtherObject\": {\n"
                           "      \"bmc.dev.TestInterface\": {\n"
                           "        \"DeviceName\": \"other\"\n"
                           "      }\n"
                           "    }\n"
                           "  }\n"
                           "}";

    mc::mutable_dict connector;
    connector["SystemId"]      = 1;
    connector["GroupPosition"] = std::string("05");
    connector["Slot"]          = 1;

    // create_component_device 在找不到 unit 对象时会抛出 mc::parse_error_exception
    // 这个异常会从 create_devices_object 传播到 add_device
    // 但 add_device 没有 try-catch，所以异常会继续传播
    // 因此 add_device 会抛出异常
    EXPECT_THROW(
        device_manager::get_instance().add_device(m_test_service.get(), csr_json, connector),
        mc::parse_error_exception);

    // 验证设备对象未被创建（因为 create_devices_object 失败）
    auto device_object = device_topo::get_instance().get_device_object("05");
    EXPECT_EQ(device_object, nullptr);
}

// 测试 add_device 当兼容驱动缺失时抛出异常
TEST_F(ManagerTest, add_device_driver_not_found) {
    std::string csr_json = "{\n"
                           "  \"Unit\": {\n"
                           "    \"Type\": \"PCIeNicCard\",\n"
                           "    \"Name\": \"PCIeNicCard_1\",\n"
                           "    \"Compatible\": [\"nonexistent_driver\"]\n"
                           "  },\n"
                           "  \"Objects\": {\n"
                           "    \"PCIeNicCard_1\": {\n"
                           "      \"bmc.dev.TestInterface\": {\n"
                           "        \"DeviceName\": \"missing_driver_card\"\n"
                           "      }\n"
                           "    }\n"
                           "  }\n"
                           "}";

    mc::mutable_dict connector;
    connector["SystemId"]      = 1;
    connector["GroupPosition"] = std::string("05_DRIVER");
    connector["Slot"]          = 1;

    EXPECT_THROW(
        device_manager::get_instance().add_device(m_test_service.get(), csr_json, connector),
        mc::parse_error_exception);

    auto residual = device_topo::get_instance().get_device_object("05_DRIVER");
    EXPECT_EQ(residual, nullptr);
}

// 测试 add_device 中 process_topology_object 返回空结果的情况
TEST_F(ManagerTest, add_device_empty_topology_result) {
    // 创建一个没有拓扑的 CSR
    std::string csr_json = "{\n"
                           "  \"Unit\": {\n"
                           "    \"Type\": \"PCIeNicCard\",\n"
                           "    \"Name\": \"PCIeNicCard_1\",\n"
                           "    \"Compatible\": [\"test_driver\"]\n"
                           "  },\n"
                           "  \"Objects\": {\n"
                           "    \"PCIeNicCard_1\": {\n"
                           "      \"bmc.dev.TestInterface\": {\n"
                           "        \"DeviceName\": \"test_card\"\n"
                           "      }\n"
                           "    }\n"
                           "  }\n"
                           "}";

    mc::mutable_dict connector;
    connector["SystemId"]      = 1;
    connector["GroupPosition"] = std::string("06");
    connector["Slot"]          = 1;

    EXPECT_NO_THROW(
        device_manager::get_instance().add_device(m_test_service.get(), csr_json, connector));

    // 验证设备对象已创建（即使没有拓扑）
    auto device_object = device_topo::get_instance().get_device_object("06");
    EXPECT_NE(device_object, nullptr);

    // 清理
    auto     csr_variant = mc::json::json_decode(csr_json).as_dict();
    mc::dict remove_connector{{"SystemId", 1},
                              {"GroupPosition", std::string("06")},
                              {"Slot", 1},
                              {"Unit", csr_variant["Unit"]}};
    device_manager::get_instance().remove_device(remove_connector);
}

// 测试 add_device 中 add_topology 失败的情况（拓扑格式错误）
TEST_F(ManagerTest, add_device_topology_add_failed) {
    auto csr_str = mc::filesystem::read_file("./tests_data/csr/topology.sr");
    MC_ASSERT_THROW(csr_str, mc::invalid_arg_exception, "Failed to read csr file: ${file}",
                    ("file", "./tests_data/csr/topology.sr"));
    auto csr_variant = mc::json::json_decode(*csr_str).as_dict();

    mc::mutable_dict connector;
    connector["SystemId"]      = 1;
    connector["GroupPosition"] = std::string("07");
    connector["Slot"]          = 1;
    connector["Buses"]         = mc::variants{"I2c_A", "I2c_B"};

    // add_device 应该不会抛出异常，即使拓扑添加失败
    EXPECT_NO_THROW(
        device_manager::get_instance().add_device(m_test_service.get(), *csr_str, connector));

    // 验证设备对象已创建（即使拓扑添加可能失败）
    auto device_object = device_topo::get_instance().get_device_object("07");
    EXPECT_NE(device_object, nullptr);

    // 清理
    mc::dict remove_connector{{"SystemId", 1},
                              {"GroupPosition", std::string("07")},
                              {"Slot", 1},
                              {"Unit", csr_variant["Unit"]}};
    device_manager::get_instance().remove_device(remove_connector);
}

// 测试 add_device 中 finalize_device_setup 抛出异常的情况
TEST_F(ManagerTest, add_device_finalize_setup_exception) {
    // 创建一个会导致 finalize_device_setup 失败的 CSR（例如缺少必要的对象）
    std::string csr_json = "{\n"
                           "  \"Unit\": {\n"
                           "    \"Type\": \"PCIeNicCard\",\n"
                           "    \"Name\": \"PCIeNicCard_1\",\n"
                           "    \"Compatible\": [\"test_driver\"]\n"
                           "  },\n"
                           "  \"Objects\": {\n"
                           "    \"PCIeNicCard_1\": {\n"
                           "      \"bmc.dev.TestInterface\": {\n"
                           "        \"DeviceName\": \"test_card\"\n"
                           "      }\n"
                           "    }\n"
                           "  }\n"
                           "}";

    mc::mutable_dict connector;
    connector["SystemId"]      = 1;
    connector["GroupPosition"] = std::string("08");
    connector["Slot"]          = 1;

    // add_device 应该不会抛出异常，即使 finalize_device_setup 可能失败
    EXPECT_NO_THROW(
        device_manager::get_instance().add_device(m_test_service.get(), csr_json, connector));

    // 验证设备对象已创建（即使 finalize_device_setup 可能失败）
    auto device_object = device_topo::get_instance().get_device_object("08");
    EXPECT_NE(device_object, nullptr);

    // 清理
    auto     csr_variant = mc::json::json_decode(csr_json).as_dict();
    mc::dict remove_connector{{"SystemId", 1},
                              {"GroupPosition", std::string("08")},
                              {"Slot", 1},
                              {"Unit", csr_variant["Unit"]}};
    device_manager::get_instance().remove_device(remove_connector);
}

// ==================== device_manager::remove_device 额外错误处理场景测试 ====================

// 测试 remove_device 中 load_compatible_driver 失败的情况
TEST_F(ManagerTest, remove_device_load_driver_failed) {
    auto csr_str = mc::filesystem::read_file("./tests_data/csr/test_device.sr");
    MC_ASSERT_THROW(csr_str, mc::invalid_arg_exception, "Failed to read csr file: ${file}",
                    ("file", "./tests_data/csr/test_device.sr"));
    auto csr_variant = mc::json::json_decode(*csr_str).as_dict();

    mc::mutable_dict connector;
    connector["SystemId"]      = 1;
    connector["GroupPosition"] = std::string("09");
    connector["Slot"]          = 1;

    device_manager::get_instance().add_device(m_test_service.get(), *csr_str, connector);
    auto device_object = device_topo::get_instance().get_device_object("09");
    EXPECT_NE(device_object, nullptr);

    // 保存原始的 Unit 信息，避免修改 csr_variant
    mc::dict original_unit = csr_variant["Unit"].as<mc::dict>();

    // 创建修改后的 Unit 副本，使其无法加载驱动
    // 通过遍历 original_unit 创建真正的副本，避免修改原始数据
    mc::mutable_dict modified_unit;
    for (auto it = original_unit.begin(); it != original_unit.end(); ++it) {
        modified_unit.insert(it->key, it->value);
    }
    modified_unit["Compatible"] = mc::variants{"nonexistent_driver"};

    mc::dict connector_with_invalid_unit{{"SystemId", 1},
                                         {"GroupPosition", std::string("09")},
                                         {"Slot", 1},
                                         {"Unit", modified_unit}};

    // remove_device 应该不会抛出异常，即使驱动加载失败
    EXPECT_NO_THROW(device_manager::get_instance().remove_device(connector_with_invalid_unit));

    // 当驱动加载失败时，设备对象不会被移除（因为异常处理时没有调用 remove_device_object）
    auto residual_object = device_topo::get_instance().get_device_object("09");
    EXPECT_NE(residual_object, nullptr);

    // 使用正确的 Unit 信息再次尝试移除（使用保存的原始 Unit 信息）
    mc::dict connector_with_valid_unit{{"SystemId", 1},
                                       {"GroupPosition", std::string("09")},
                                       {"Slot", 1},
                                       {"Unit", original_unit}};
    EXPECT_NO_THROW(device_manager::get_instance().remove_device(connector_with_valid_unit));
    auto final_object = device_topo::get_instance().get_device_object("09");
    // 使用正确的 Unit 信息后，驱动应该能够成功加载，设备对象应该被移除
    EXPECT_EQ(final_object, nullptr)
        << "Device object should be removed after successful driver load";
}

// 测试 remove_device 中 device.stop 抛出异常的情况
TEST_F(ManagerTest, remove_device_stop_exception) {
    auto csr_str = mc::filesystem::read_file("./tests_data/csr/test_device.sr");
    MC_ASSERT_THROW(csr_str, mc::invalid_arg_exception, "Failed to read csr file: ${file}",
                    ("file", "./tests_data/csr/test_device.sr"));
    auto csr_variant = mc::json::json_decode(*csr_str).as_dict();

    mc::mutable_dict connector;
    connector["SystemId"]      = 1;
    connector["GroupPosition"] = std::string("0A");
    connector["Slot"]          = 1;

    device_manager::get_instance().add_device(m_test_service.get(), *csr_str, connector);
    auto device_object = device_topo::get_instance().get_device_object("0A");
    EXPECT_NE(device_object, nullptr);

    // 正常移除设备（测试 stop 不会抛出异常的情况）
    mc::dict connector_with_unit{{"SystemId", 1},
                                 {"GroupPosition", std::string("0A")},
                                 {"Slot", 1},
                                 {"Unit", csr_variant["Unit"]}};

    // remove_device 应该不会抛出异常，即使 stop 可能失败
    EXPECT_NO_THROW(device_manager::get_instance().remove_device(connector_with_unit));

    // 验证设备对象已被移除
    auto final_object = device_topo::get_instance().get_device_object("0A");
    EXPECT_EQ(final_object, nullptr);
}